<?php

namespace App\Http\Requests\Staff;

use App\Http\Models\App\App;
use App\Http\Models\Staff\Staff;
use App\Http\Models\Staff\StaffAppRelation;
//use App\Http\Models\Station\SysUser;
use App\Http\Requests\Common\BaseRequest as Request;
use Cache;

class AuthRequest extends Request
{
    //
    public function login()
    {
        $data = [
            'title'        => '员工|登陆',
            'host'         => $this->get('host'),
            'stations'     => config('station'),
            'selected'     => '1010',
            'redirect_url' => $this->get('redirect_uri'),
        ];
        return view('staff.auth.login', compact('data'));
    }
    //
    public function check_login()
    {
        /*
        处理逻辑
        1-查找app信息;
        2-查找该用户是否已关联该app;
        3-查找用户信息;
        4-把当前用户信息写入session;
        5-生成ticket,并把ticket作为缓存键生成一条与用户有关的记录;
        6-根据重定向地址把ticket带回去;
         */
        $rules = [
            "station_id"   => "required|in:yj,yc,yx",
            "host"         => "required|exists:app,host",
            "account"      => "required|min:2|max:80",
            "password"     => "required|min:2|max:80",
            "redirect_url" => "required|url|min:2|max:80",
        ];
        $message = array(
            "required" => ":attribute不能为空！",
            "min"      => ":attribute长度必能少于:min！",
            "max"      => ":attribute长度不能大于:max！",
            "exists"   => ":attribute不存在！",
            "in"       => ":attribute不合法！",
        );
        $attributes = array(
            "account"      => "账号名",
            "station_id"   => "站场编码",
            "password"     => "账号密码",
            "host"         => "应用域名",
            "redirect_url" => "重定向地址",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //
        $app_id = App::where('host', $data['host'])->where('status', 1)->pluck('id');
        //读取售票系统用户数据
        $remote = [];
        // $model  = new SysUser($data['station_id']);
        // $remote = $model->where('LoginID', $data['account'])
        //     ->select('ID', 'LoginID', 'Pwd', 'UserName', 'Mobile', 'EMail', 'IsValid')
        //     ->first();
        //读取CAS用户数据
        $local = Staff::where('account', $data['account'])->pluck('id');
        if (is_null($remote) && is_null($local)) {
            return self::_json([], 1, "账号不存在！");
        }
        //假如有售票数据，则更新或者插入数据
        if ($remote) {
            $date              = date('Y-m-d H:i:s');
            $clean             = [];
            $clean['name']     = $remote->UserName;
            $clean['account']  = $remote->LoginID;
            $clean['password'] = $remote->Pwd;
            $clean['status']   = $remote->IsValid;
            if ($remote->Mobile) {
                $clean['mobile'] = $remote->Mobile;
                $clean['email']  = $remote->EMail;
            }
            //
            if (is_null($local)) {
                $clean['created_at'] = $date;
                if (!Staff::insert($clean)) {
                    return self::_json([], -1, "新增售票员工到CAS失败！");
                }
            } else {
                /*防止CAS修改密码不生效,故在同步时不该密码*/
                unset($clean['password']);
                $clean['updated_at'] = $date;
                if (!Staff::where('id', $local)->update($clean)) {
                    return self::_json([], -1, "同步售票员工到CAS失败！");
                }
            }
        }
        //读取CAS用户数据
        $account = $data['account'];
        $password = md5($data['password']);
        $model   = Staff::where(function ($query) use ($account) {
            $query->where('account', $account);
            $query->orWhere('mobile', $account);
            $query->orWhere('email', $account);
        });
        $staff = $model->where('status', 1)
            ->where('station_id', $data['station_id'])
            ->where('password', $password)
            ->select('id', 'name', 'mobile', 'account', 'mobile', 'dept_id', 'post_id')
            ->first();
        if (empty($staff)) {
            return self::_json([], 1, "账号或者密码错误!");
        }
        //
        $relation = StaffAppRelation::where('app_id', $app_id)
            ->where('staff_id', $staff->id)
            ->where('status',1)
            ->first();
        if (empty($relation)) {
            return self::_json([], 1, '用户尚未关联该应用！');
        }
        //
        $ticket      = str_random(28);
        $cacheExpire = 120;
        session([$ticket => $ticket]);
        //用户详细信息
        $detail = StaffRequest::Detail($app_id, $staff->id, $ticket);
        Cache::tags('ticket')->put($ticket, ['ticket' => $ticket, 'app_id' => $app_id, 'staff_id' => $staff->id], $cacheExpire);
        Cache::tags('staff')->put($ticket, $detail, $cacheExpire);
        //
        $redirect_uri = $data['redirect_url'] . '?ticket=' . $ticket;
        return self::_json(['ticket'=>$ticket], 0, '登录成功!', $redirect_uri);
    }
    //
    public function logout()
    {
        $keys = ['host', 'ticket', 'redirect_uri'];
        $data = $this->only($keys);
        $app  = App::where('host', $data['host'])->where('status', 1)
            ->select('id', 'name', 'host')
            ->first();
        if (is_null($app)) {
            return redirect()->away($data['redirect_uri']);
        }
        //
        session([$data['ticket'] => null]);
        Cache::tags('ticket')->forget($data['ticket']);
        Cache::tags('staff')->forget($data['ticket']);
        return redirect()->away($data['redirect_uri']);
    }
}
